# -*- coding: UTF-8 -*-

import datetime
from django.utils import simplejson
from django.http import HttpResponse
from django.views.generic.base import View



class JSONDateTimeEncoder(simplejson.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (datetime.date, datetime.datetime)):
            return obj.strftime('%d/%m/%Y') 
        #~ return obj.isoformat()
        else:
            return simplejson.JSONEncoder.default(self, obj)

class AJAXFallbackView(View):
# views (get, post, etc) must return (context, template) instead of rendering it themselves
# similar to auto_render

    valid_json_start = ['"', '[', '{']
    valid_json_end = ['"', ']', '}']
    allow_empty = True

    def dispatch(self, request, *args, **kwargs):
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed
        self.request = request
        self.args = args
        self.kwargs = kwargs
        template, ctx = handler(request, *args, **kwargs)
        return self.render(ctx)


    def render(self, context):
        json = simplejson.dumps(context, cls=JSONDateTimeEncoder)
        callback = self.request.GET.get('callback')
        if callback:
            if json[0] not in self.valid_json_start or json[-1] not in self.valid_json_end:
                json = ''.join(['"',json,'"'])
                return HttpResponse('%s(%s)' % (callback,json),mimetype='application/javascript')
        return HttpResponse(json, mimetype='application/json')


